package com.zhuyuan.swagger;

import com.zhuyuan.core.constant.Oauth2Constants;
import com.zhuyuan.swagger.properties.SpringDocProperties;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 张琳凯
 * @Description: swagger 配置类
 * @DateTime: 2025/2/7 10:47
 **/
@RequiredArgsConstructor
@AutoConfigurationPackage
@EnableConfigurationProperties(SpringDocProperties.class)
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public class SpringDocAutoConfig {
    private final SpringDocProperties swaggerProperties;
//    private final ServiceInstance serviceInstance;
    @Bean
    public OpenAPI springOpenApi() {
        OpenAPI openAPI = new OpenAPI();
        openAPI.setInfo(convertInfo(swaggerProperties));
        openAPI.schemaRequirement(Oauth2Constants.HEADER_TOKEN_KEY, this.securityScheme());
        openAPI.addSecurityItem(new SecurityRequirement().addList(Oauth2Constants.HEADER_TOKEN_KEY));
//        List<Server> serverList = new ArrayList<>();
//        String path = swaggerProperties.getServices().get(serviceInstance.getServiceId());
//        serverList.add(new Server().url(swaggerProperties.getGateway() + "/" + path));
//        openAPI.setServers(serverList);
        return openAPI;
    }
    //基本信息
    private Info convertInfo(SpringDocProperties infoProperties) {
        Info info = new Info();
        info.setTitle(infoProperties.getTitle());
        info.setDescription(infoProperties.getDescription());
        info.setContact(infoProperties.getContact());
        info.setLicense(infoProperties.getLicense());
        info.setVersion(infoProperties.getVersion());
        return info;
    }
    //token
    private SecurityScheme securityScheme() {
        SecurityScheme securityScheme = new SecurityScheme();
        securityScheme.setType(SecurityScheme.Type.APIKEY);
        securityScheme.setName(Oauth2Constants.HEADER_TOKEN_KEY);
        securityScheme.setIn(SecurityScheme.In.HEADER);
        return securityScheme;
    }
}
